package com.cmc.cloud.cmclink.doc.util;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;



/**
 * URL下载文件
 *
 * @author 集运管理员
 */
public class UrlDownloader {

    public static final int NUMERAL = 1024;
    public static final int MAX_SIZE = 10;


    public static ByteArrayOutputStream downloadToByteArrayOutputStream(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求参数
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(10000);
        connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        // 检查响应状态
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("下载文件失败，响应码：" + responseCode);
        }

        try (InputStream inputStream = connection.getInputStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.flush();
            return outputStream;
        } finally {
            connection.disconnect();
        }
    }


    /**
     * 下载小型文件（小于10MB）
     * @param fileUrl 文件URL地址
     * @param savePath 本地保存路径
     * @throws IOException 下载异常
     */
    public static void downloadSmallFile(String fileUrl, String savePath) throws IOException {
        URL url = new URL(fileUrl);
        try (InputStream inputStream = url.openStream();
             OutputStream outputStream = new FileOutputStream(savePath)) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }

    /**
     * 下载大型文件（使用NIO传输）
     * @param fileUrl 文件URL地址
     * @param savePath 本地保存路径
     * @throws IOException 下载异常
     */
    public static void downloadLargeFile(String fileUrl, String savePath) throws IOException {
        URL website = new URL(fileUrl);
        try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
             FileOutputStream fos = new FileOutputStream(savePath)) {

            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        }
    }

    /**
     * 下载文件并设置网络参数
     * @param fileUrl 文件URL地址
     * @param savePath 本地保存路径
     * @param fileName 文件名
     * @throws IOException 下载异常
     */
    public static void downloadWithConfiguration(String fileUrl, String savePath, String fileName)
            throws IOException {

        // 创建保存目录
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }

        URL url = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(3000);
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");

        try (InputStream inputStream = conn.getInputStream();
             FileOutputStream fos = new FileOutputStream(savePath + File.separator + fileName)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }


        } finally {
            conn.disconnect();
        }
    }

    /**
     * 获取文件大小
     * @param fileUrl 文件URL地址
     * @return 文件大小（字节）
     * @throws IOException 获取异常
     */
    public static long getFileSize(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("HEAD");
        long size = conn.getContentLengthLong();
        conn.disconnect();
        return size;
    }

    public static void main(String[] args) {
        try {
            String fileUrl = "https://www.example.com/file.zip";
            String savePath = "downloads";
            String fileName = "file.zip";

            // 获取文件大小选择下载方式
            long fileSize = getFileSize(fileUrl);
            System.out.println("文件大小: " + fileSize + " 字节");

            if (fileSize < MAX_SIZE * NUMERAL * NUMERAL) {
                // 小于10MB
                downloadSmallFile(fileUrl, savePath + File.separator + fileName);
            } else {
                downloadLargeFile(fileUrl, savePath + File.separator + fileName);
            }

            System.out.println("文件下载完成!");

        } catch (IOException e) {
            System.err.println("下载失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
